#include "Acceptor.h"

#include "EventLoop.h"
#include "Logger.h"

Acceptor::Acceptor(EventLoop* loop, InetAddress addr)
    : loop_(loop), accept_socket_(createNonblocking()), accept_channel_(accept_socket_.Fd(), loop_), listening_(false) {
    accept_socket_.SetNonBlock();
    accept_socket_.SetReuseAddress(true);
    accept_socket_.SetReusePort(true);
    accept_socket_.Bind(addr);
    // listen -- trigger read event -- execute callback(accept) -- connfd -- channel --wakeup subloop
    accept_channel_.SetReadCallback(std::bind(&Acceptor::HandleRead, this));
}

// mainloop 设置
void Acceptor::SetConnectionCallback(const NewConnectionCallback& cb) {
    new_connection_callback_ = cb;
}

void Acceptor::HandleRead() {
    InetAddress addr;
    int connfd = accept_socket_.Accept(&addr);
    // channel
    LOG_INFO("accept client, connfd = %d", connfd);
    if (new_connection_callback_) {
        new_connection_callback_(connfd, addr);
    } else {
        // UNDERSTAND:
        close(connfd);
    }
}

void Acceptor::Listen() {
    listening_ = true;
    accept_channel_.EnableRead();  // accept_channel_注册至Poller
    accept_socket_.Listen();
}

Acceptor::~Acceptor() {
    accept_channel_.DisableAll();
    accept_channel_.Remove();
}
